package com.cn.api.client;

import com.cn.common.TopicRouteData;
import com.cn.common.processor.ProcessorCode;
import com.cn.msg.Message;
import com.cn.remote.RemoteClient2;
import com.cn.util.RemotingSerializable;

import java.nio.charset.Charset;

public class ClientController {

    private RemoteClient2 remoteClient2;

    private String address;
    private final String bodys = "default";

    public ClientController(String address) {
        this.address = address;
        this.remoteClient2 = new RemoteClient2();
    }

    public void queryMsgById(String id) {

    }

    public TopicRouteData queryAllTopic() {
        System.out.println("监控到api调用请求！");
        Message message = new Message();
        message.setType((byte) 19);
        message.setFlag((byte) 1);
        message.setByteBodys(bodys.getBytes(Charset.forName("utf-8")));
        message.setLength(message.getByteBodys().length);
        message.setBody(null);
        message.setNettyRequestWrapperCode((byte) ProcessorCode.pull_default);
        try {
            byte[] result = this.remoteClient2.invokeMsg(message, address, 30000);
            if (result != null) {
                TopicRouteData topicRouteData = new TopicRouteData();
                topicRouteData = RemotingSerializable.decode(result, TopicRouteData.class);
                if (topicRouteData != null) {
                    return topicRouteData;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public void start() {
        this.remoteClient2.start();
    }

    public void stop() {
        this.remoteClient2.shutdown();
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
